/*
 * @Author: caihongtai caihongtai
 * @Date: 2025-02-15 21:51:04
 * @LastEditors: caihongtai caihongtai
 * @LastEditTime: 2025-02-16 15:14:53
 * @FilePath: /ai-interview-vue/src/utils/typewriter.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */


export const typewriterDirective = (el, binding) => {
    const text = binding.value || el.innerText
    const speed = binding.arg || 100 // 默认打印速度

    // 清空原有内容
    el.innerText = ''

    let index = 0
    const timer = setInterval(() => {
        if (index < text.length) {
            el.innerText += text[index]
            index++
        } else {
            clearInterval(timer)
            // 打印完成后触发回调
            if (binding.modifiers.callback) {
                binding.instance?.$emit('typewriter-complete')
            }
        }
    }, speed)

    // 保存定时器，以便在需要时清除
    el._typewriterTimer = timer
}

// 注册指令
export default {
    mounted(el, binding) {
        typewriterDirective(el, binding)
    },
    beforeUnmount(el) {
        // 清除定时器
        if (el._typewriterTimer) {
            clearInterval(el._typewriterTimer)
        }
    },
    updated(el, binding) {
        // 如果值发生变化，重新执行打印
        if (binding.value !== binding.oldValue) {
            if (el._typewriterTimer) {
                clearInterval(el._typewriterTimer)
            }
            typewriterDirective(el, binding)
        }
    }
}

